package com.neu.controller;


import com.github.pagehelper.PageInfo;
import com.neu.common.AutoLog;
import com.neu.common.CaptureConfig;
import com.neu.common.Result;
import com.neu.entity.Admin;
import com.neu.entity.Params;
import com.neu.service.AdminService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

//    @GetMapping("/start")
//    public Result start(){
//        return Result.success("这是你的第一个springboot项目工程！已经启动");
//    }
    @GetMapping
    public Result findAll(){
        List<Admin> list = adminService.getAll();

        return Result.success(list);

    }

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Admin> info = adminService.findBySearch(params);
        return Result.success(info);
    }

    @PostMapping
    public Result add(@RequestBody Admin admin){
        if(admin.getId() == null){
            adminService.add(admin);
        }else{
            adminService.update(admin);
        }

        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        adminService.delete(id);
        return Result.success();
    }

    @PostMapping("/login")
    @AutoLog("登录该系统")
    public Result login(@RequestBody Admin admin, @RequestParam String key, HttpServletRequest request){
        //判断验证码对不对
        if(!admin.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))){
            //如果不相等，说明验证不通过
            CaptchaUtil.clear(request);

            return  Result.error("验证码不正确");
        }
        Admin loginUser = adminService.login(admin);
        CaptureConfig.CAPTURE_MAP.remove(key);
        return Result.success(loginUser);
    }
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.add(admin);

        return Result.success();
    }

}
